package com.eascs.spider.zhaopin.schdule;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eascs.spider.zhaopin.actor.Job51Actor;
import com.eascs.spider.zhaopin.proj.SearchFilter;
import com.eascs.spider.zhaopin.util.PropertiesUtil;

public class TaskManager {

	private static Logger logger = LoggerFactory.getLogger(TaskManager.class);
	public static Queue<SearchFilter> queue = new ConcurrentLinkedQueue<>();
	private static ExecutorService executors;
	private static TaskManager instance;
	
	
	public static TaskManager init(){
		executors = Executors.newFixedThreadPool(10);
		Schdule schdule = new Schdule();
		schdule.start();
		instance = new TaskManager();
		logger.info("任务管理器初始化完毕");
		return instance;
	}
	
	public static synchronized TaskManager getInstance(){
		return instance==null?init():instance;
	}
	
	public void addFilter(SearchFilter filter){
		queue.add(filter);
	}
	
	static class Schdule extends Thread{
		
		@Override
		public void run(){
			String cookie = PropertiesUtil.get51jobCookie();
			while(true){
				if(!queue.isEmpty()){
					SearchFilter filter = queue.poll();
					Job51Actor actor = new Job51Actor(cookie, filter.getKeyword(), 
							filter.getExpAddress(), filter.getAgeMin(), filter.getAgeMax());
					executors.execute(actor);
				}
			}
		}
	}
}
